package com.example.user_management_p1.mq;

import com.pojo.util.Tool;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import java.security.GeneralSecurityException;
import java.util.concurrent.TimeUnit;

public class SendCode {
    public static int sendCheckCode(String email, String from, JavaMailSender mailSender, RedisTemplate redisTemplate)
            throws GeneralSecurityException {
        try {
            boolean timecheck= redisTemplate.opsForValue().setIfAbsent(email+":gettime",1,120, TimeUnit.SECONDS);
            if (timecheck==false)
                return 0;
            String to=email,subject ="验证码",content= Tool.getCheckCode();
            redisTemplate.opsForValue().set(email+":CheckCode",content,180, TimeUnit.SECONDS);
            // 创建一个邮件对象
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setFrom(from); // 设置发送发
            msg.setTo(to); // 设置接收方
            msg.setSubject(subject); // 设置邮件主题
            msg.setText(content); // 设置邮件内容
            // 发送邮件
            mailSender.send(msg);
        }catch (Exception e){
            return 0;
        }
        return 1;
    }
}
